package zm.irc.threads;

import org.apache.log4j.Logger;

import zm.irc.cfg.BaiduTransferConfig;
import zm.irc.dao.BaiduTransDao;
import zm.irc.dto.TranslateInfo;
import zm.irc.ioc.annotation.AutoWired;
import zm.irc.ioc.annotation.Service;
import zm.irc.ioc.beanActoin.AfterContexinItialize;
import zm.irc.message.send.IrcChatMessage;
import zm.irc.msgqueue.LocalMemoryMsgQueue;


@Service(isSinglet = true)
public class TranslateThread  extends IrcThread implements AfterContexinItialize{
    public static final String queueName = "TranslateQueue_";
    private static Logger log = Logger.getLogger(MsgSendThread.class);

    @AutoWired
    private LocalMemoryMsgQueue localMemoryMsgQueue ;

    @AutoWired
    private BaiduTransferConfig baiduTransferConfig;

    @AutoWired
    private  BaiduTransDao dao;

    private volatile boolean inited = false;

    @Override
    public void doAction() {
        this.init();
        
    }

    private void init(){
        if(inited){
            return;
        }
        this.inited = true;
        localMemoryMsgQueue.registerCommonQueue(queueName);
    }

    private Object msg;

    @Override
    public void beforeLoop(){
        log.info("Transalte Thread Start.");
    }

    @Override
    public void before(){
        this.msg = localMemoryMsgQueue.getMsgFromCommonQueue(queueName);
    }

    @Override
    public void doRun() {
        try {
            if (msg != null && (msg instanceof TranslateInfo)) {
                TranslateInfo translateInfo = (TranslateInfo) msg;
                String dist = dao.transTo(translateInfo.getMsg(), translateInfo.getDistLanguage());
                IrcChatMessage chatMsg = new IrcChatMessage();
                chatMsg.setChannel(translateInfo.getChannelName());
                String msgBody = String.format(" >> %s : %s", translateInfo.getRequesterName(), dist);
                chatMsg.setMsg(msgBody);
                this.localMemoryMsgQueue.addSendQueue(chatMsg);
                Thread.sleep(1200);// Due to the translate api's QRS is only 1.
            } else {
                Thread.sleep(50);// Due to the translate api's QRS is only 1.
            }
        } catch (Exception e) {
            log.error("error", e);
        }

    }


}
